package com.boot.core.util

import cn.afterturn.easypoi.excel.ExcelExportUtil
import cn.afterturn.easypoi.excel.entity.ExportParams
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType
import org.apache.poi.ss.usermodel.Workbook
import java.io.IOException
import javax.servlet.http.HttpServletResponse

object ExcelUtil {


    fun exportExcel(list: List<*>, title: String, sheetName: String, pojoClass: Class<*>, fileName: String, isCreateHeader: Boolean, response: HttpServletResponse) {
        val exportParams = ExportParams(title, sheetName)
        exportParams.isCreateHeadRows = isCreateHeader
        defaultExport(list, pojoClass, fileName, response, exportParams)
    }

    fun exportExcel(list: List<*>, title: String, sheetName: String, pojoClass: Class<*>, fileName: String, response: HttpServletResponse) {
        defaultExport(list, pojoClass, fileName, response, ExportParams(title, sheetName))
    }

    fun exportExcel(list: List<Map<String, Any>>, fileName: String, response: HttpServletResponse) {
        defaultExport(list, fileName, response)
    }

    private fun defaultExport(list: List<*>, pojoClass: Class<*>, fileName: String, response: HttpServletResponse, exportParams: ExportParams) {
        val workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list)
        if (workbook != null)
            downLoadExcel(fileName, response, workbook)
    }

    private fun downLoadExcel(fileName: String, response: HttpServletResponse, workbook: Workbook) {
        try {
            response.characterEncoding = "UTF-8"
            response.contentType = "application/x-download"
            response.setHeader("content-Type", "application/vnd.ms-excel")
            response.setHeader("Content-Disposition",
                    "attachment;filename=$fileName.xls")
            workbook.write(response.outputStream)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun defaultExport(list: List<Map<String, Any>>, fileName: String, response: HttpServletResponse) {
        val workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF)
        if (workbook != null);
        downLoadExcel(fileName, response, workbook!!)
    }
}